package com.ruoyi.erp.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.ruoyi.common.config.DDConstant;
import com.ruoyi.common.enums.erp.ErpWeekReadStatusEnum;
import com.ruoyi.common.enums.erp.ErpWeeklyQueryEnum;
import com.ruoyi.common.enums.erp.ErpWeeklyStatusEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.dd.MessageUtil;
import com.ruoyi.erp.domain.ErpWeeklyRecord;
import com.ruoyi.erp.domain.dto.ErpWeeklyDTO;
import com.ruoyi.erp.mapper.ErpWeeklyRecordMapper;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.erp.mapper.ErpWeeklyMapper;
import com.ruoyi.erp.domain.ErpWeekly;
import com.ruoyi.erp.service.IErpWeeklyService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * 周报数据Service业务层处理
 *
 * @author yanwenliang
 * @date 2024-10-14
 */
@Service
public class ErpWeeklyServiceImpl extends ServiceImpl<ErpWeeklyMapper, ErpWeekly> implements IErpWeeklyService
{
    @Autowired
    private ErpWeeklyMapper erpWeeklyMapper;

    @Autowired
    private ErpWeeklyRecordMapper erpWeeklyRecordMapper;

    /**
     * 查询周报数据
     *
     * @param weeklyId 周报数据主键
     * @return 周报数据
     */
    @Override
    @Transactional
    public ErpWeeklyDTO selectErpWeeklyByWeeklyId(String weeklyId) {

        erpWeeklyRecordMapper.update(new ErpWeeklyRecord(), new LambdaUpdateWrapper<ErpWeeklyRecord>()
                .eq(ErpWeeklyRecord::getWeeklyId, weeklyId)
                .eq(ErpWeeklyRecord::getUserId, SecurityUtils.getUserId())
                .eq(ErpWeeklyRecord::getStatus, ErpWeekReadStatusEnum.NOT_READ.getCode())
                .set(ErpWeeklyRecord::getStatus, ErpWeekReadStatusEnum.READ.getCode())
                .set(ErpWeeklyRecord::getReadTime, new Date()));

        return erpWeeklyMapper.selectErpWeeklyByWeeklyId(weeklyId);
    }

    /**
     * 查询周报数据列表
     *
     * @param erpWeeklyDTO 周报数据
     * @return 周报数据
     */
    @Override
    public List<ErpWeeklyDTO> selectErpWeeklyList(ErpWeeklyDTO erpWeeklyDTO) {

        if (!ErpWeeklyQueryEnum.ALL.getCode().equals(erpWeeklyDTO.getQueryValue())){
            erpWeeklyDTO.setUserId(SecurityUtils.getUserId());

            erpWeeklyDTO.setReadStatus(ErpWeeklyQueryEnum.NOT_READ.getCode().equals(erpWeeklyDTO.getQueryValue()) ? ErpWeekReadStatusEnum.NOT_READ.getCode() : ErpWeekReadStatusEnum.READ.getCode());
        }

        return erpWeeklyMapper.selectErpWeeklyList(erpWeeklyDTO);
    }

    /**
     * 新增周报数据
     *
     * @param erpWeekly 周报数据
     * @return 结果
     */
    @Override
    @Transactional
    public boolean insertErpWeekly(ErpWeekly erpWeekly) throws ApiException {
        if (ObjectUtils.isEmpty(erpWeekly.getWeeklyId())){
            erpWeekly.setWeeklyId(IdWorker.getIdStr());
            erpWeekly.setCreateTime(DateUtils.getNowDate());
            erpWeekly.setCreateBy(SecurityUtils.getUsername());
            erpWeekly.setUserId(SecurityUtils.getUserId());
            erpWeekly.setSubmitTime(ErpWeeklyStatusEnum.SUBMIT.getCode().equals(erpWeekly.getWeeklyStatus()) ? DateUtils.getNowDate() : null);
        } else {
            ErpWeekly weekly = erpWeeklyMapper.selectById(erpWeekly.getWeeklyId());
            erpWeekly.setUpdateTime(DateUtils.getNowDate());
            erpWeekly.setUpdateBy(SecurityUtils.getUsername());
            // 周报状态为未提交并且准备提交，则设置提交时间
            erpWeekly.setSubmitTime(ErpWeeklyStatusEnum.NOT_SUBMIT.getCode().equals(weekly.getWeeklyStatus()) && ErpWeeklyStatusEnum.SUBMIT.getCode().equals(erpWeekly.getWeeklyStatus()) ? DateUtils.getNowDate() : weekly.getSubmitTime());
        }
        boolean flag = this.saveOrUpdate(erpWeekly);
        if("1".equals(erpWeekly.getWeeklyStatus()) && flag){

            // 添加分享人列表
            String[] userIds = erpWeekly.getShareList().split(",");
            for (String userId : userIds) {
                ErpWeeklyRecord erpWeeklyRecord = new ErpWeeklyRecord();
                erpWeeklyRecord.setWeeklyId(erpWeekly.getWeeklyId());
                erpWeeklyRecord.setStatus("0");
                erpWeeklyRecord.setUserId(userId);
                erpWeeklyRecordMapper.insert(erpWeeklyRecord);
            }

            // todo 提交的周报发送钉钉通知
//            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
//            msg.setMsgtype("markdown");
//            msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
//            msg.getMarkdown().setTitle(erpWeekly.getCreateBy() + "提交了周报");
//            StringBuilder text = new StringBuilder();
//            text.append("## "+ erpWeekly.getCreateBy() + "提交了周报");
//            text.append("  \n  ");
//            text.append("本周进展："+ erpWeekly.getWeeklyContent());
//            text.append("  \n  ");
//
//            String url = "1".equals(erpWeekly.getDeviceFlag()) ?  "erp/weeklyDetails/"+ erpWeekly.getWeeklyId() : "erp/weeklyList?weeklyId="+ erpWeekly.getWeeklyId();
//            text.append("[立即查看](" + DDConstant.DD_FRONT_URL + DDConstant.FRONT_URL_HOST + url +")");
//            msg.getMarkdown().setText(text.toString());
//            MessageUtil.send(erpWeekly.getShareList(), msg);
        }

        return flag;
    }

    /**
     * 修改周报数据
     *
     * @param erpWeekly 周报数据
     * @return 结果
     */
    @Override
    public int updateErpWeekly(ErpWeekly erpWeekly)
    {
        erpWeekly.setUpdateTime(DateUtils.getNowDate());
        return erpWeeklyMapper.updateErpWeekly(erpWeekly);
    }

    /**
     * 批量删除周报数据
     *
     * @param weeklyIds 需要删除的周报数据主键
     * @return 结果
     */
    @Override
    public int deleteErpWeeklyByWeeklyIds(String[] weeklyIds)
    {
        return erpWeeklyMapper.deleteErpWeeklyByWeeklyIds(weeklyIds);
    }

    /**
     * 删除周报数据信息
     *
     * @param weeklyId 周报数据主键
     * @return 结果
     */
    @Override
    public int deleteErpWeeklyByWeeklyId(String weeklyId)
    {
        return erpWeeklyMapper.deleteErpWeeklyByWeeklyId(weeklyId);
    }

    /**
     * 获取最近提交的周报数据
     * @return
     */
    @Override
    public ErpWeekly getLatestWeekly(ErpWeekly erpWeekly) {
        return erpWeeklyMapper.selectOne(new LambdaQueryWrapper<ErpWeekly>()
                .eq(ErpWeekly::getUserId, SecurityUtils.getUserId())
                .eq(ErpWeekly::getWeeklyStatus, erpWeekly.getWeeklyStatus())
                .orderByDesc(ErpWeekly::getCreateTime).last("LIMIT 1"));
    }

    /**
     * 周报统计
     * @return
     */
    @Override
    public Map<String, Integer> weeklyStatistics() {

        return erpWeeklyMapper.weeklyStatistics(SecurityUtils.getUserId());
    }
}
